package com.ruoyi.lession.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruoyi.lession.entily.Order;
import com.ruoyi.lession.mapper.OrderMapper;
import com.ruoyi.lession.service.QuestService;
import com.ruoyi.lession.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RequestMapping("wxpay")
@RestController
@CrossOrigin
public class WeixinController {
    //    @Autowired
//    PayLogServiceFeign payLogServiceFeign;

    @Autowired
    private OrderMapper orderMapper;
    @RequestMapping("pay")
    public Map<String,Object> pay(@RequestParam("oid") String oid) {

        Map<String,Object> map = new HashMap<String,Object>();

        // 查询数据库，拿到支付具体金额
//        TbPayLog payLog = null; // payLogServiceFeign.getOne(payLogId);
//        if(payLog==null){
//            map.put("status",5000);
//            map.put("msg","订单信息错误");
//            return map;
//        }

        //查询订单
        QueryWrapper<Order> orderFormQueryWrapper = new QueryWrapper<>();
        orderFormQueryWrapper.eq("oid",oid);
        List<Order> list = orderMapper.selectList(orderFormQueryWrapper);
        Order order = list.get(0);
        //为订单添加支付状态
        order.setPayment("微信支付");

        String orderId = UUID.randomUUID().toString().substring(10);

        order.setOrderid(orderId);
        orderMapper.update(order,orderFormQueryWrapper);

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", "wxab8acb865bb1637e");
        paramMap.put("mch_id", "11473623");
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("body", "和尚集团");
        paramMap.put("out_trade_no", orderId);
//         paramMap.put("total_fee", payLog.getTotalFee().intValue()+"00");
        paramMap.put("total_fee", order.getPrice()+"");
        paramMap.put("spbill_create_ip", "120.78.199.92");
        paramMap.put("notify_url", "http://www.lizi.cn/wchatPay/notify");
        paramMap.put("trade_type", "NATIVE");

        try {
            String generateSignedXml = WXPayUtil.generateSignedXml(paramMap, "2ab9071b06b9f739b950ddb41db2690d");
            System.out.println(generateSignedXml);

            String  url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpClient client = new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(generateSignedXml);
            client.post();

            //3.获取结果
            String xmlResult = client.getContent();

            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xmlResult);
            System.out.println(xmlToMap);

            map.put("status",2000);
            map.put("msg","请求成功");
//            map.put("totalFee",payLog.getTotalFee().intValue());
            map.put("codeUrl",xmlToMap.get("code_url").toString());
            return map;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询支付结果
     * @param payLogId
     * @return
     */
    @RequestMapping("orderquery")
    public Map<String,Object> orderquery(@RequestParam("payLogId")String payLogId){

        Map<String, Object> resultMap = new HashMap<String, Object>();

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", "wxab8acb865bb1637e");
        paramMap.put("mch_id", "11473623");
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        paramMap.put("out_trade_no", payLogId);
        try {
            String generateSignedXml = WXPayUtil.generateSignedXml(paramMap, "2ab9071b06b9f739b950ddb41db2690d");
            String  url = "https://api.mch.weixin.qq.com/pay/orderquery";
            HttpClient client = new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(generateSignedXml);
            client.post();

            //3.获取结果
            String xmlResult = client.getContent();

            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xmlResult);
            System.out.println(xmlToMap.get("trade_state").toString()+"---axmlToMap======================"+xmlToMap);
            if(xmlToMap.get("trade_state").toString().equals("SUCCESS")){

                //更改数据库状态就行了。


                resultMap.put("status",2000);
                resultMap.put("msg","订单查询成功");
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("orderid",payLogId);
                List<Order> list = orderMapper.selectList(wrapper);
                Order orderForm = list.get(0);
                orderForm.setStatus("已支付");
                orderMapper.update(orderForm,wrapper);
                return resultMap;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultMap.put("status",5000);
        resultMap.put("msg","订单查询失败");
        return resultMap;


    }

    /**
     * 支付成功后，微信进行回调通知咱们代码
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("notifyUrl")
    public String notifyUrl(HttpServletRequest request, HttpServletResponse response){

        try {
            //支付成功后，这个方法会接受到一条消息，消息是流形式
            InputStream inStream = request.getInputStream();
            //把消息流转换成文本类型
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            String result = new String(outSteam.toByteArray(), "UTF-8");
            System.out.println("result====="+result);
            Map<String, String> map = WXPayUtil.xmlToMap(result.toString());
            System.out.println("map====="+map);
            String return_code = map.get("event_type");

            if(!return_code.equals("TRANSACTION.SUCCESS")) {
                return "error";
            }

            /**
             * 查询订单表中金额和微信返回金额是否一致，如果不一致，继续给微信返回error
             * 如果微信金额和咱们数据库金额一致，更改订单状态
             */
            String resultAppid = map.get("appid");
            String total_fee = map.get("total_fee");
            String out_trade_no = map.get("out_trade_no");


            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;


    }





    public static void main(String[] args) {

        String orderId = UUID.randomUUID().toString().substring(10);

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("appid", "wxab8acb865bb1637e"); // 公众号id
        paramMap.put("mch_id", "11473623"); // 商户号id
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr()); // 签名算法，可以理解为密钥
        paramMap.put("body", "栗子支付");
        paramMap.put("out_trade_no", orderId);
//        paramMap.put("amount","{'total':1}"); 新版本写法
        paramMap.put("total_fee", "1");
        paramMap.put("spbill_create_ip", "120.78.167.80"); // ip白名单
        paramMap.put("notify_url", "http://www.lizi.cn/wchatPay/notify");
        paramMap.put("trade_type", "NATIVE"); // 这是觉得公众号支付，还是扫名支付，或post机支付等

        try {
            String generateSignedXml = WXPayUtil.generateSignedXml(paramMap, "2ab9071b06b9f739b950ddb41db2690d");
            System.out.println(generateSignedXml);

            String  url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpClient client = new HttpClient(url);
            client.setHttps(true);
            client.setXmlParam(generateSignedXml);
            client.post();

            //3.获取结果
            String xmlResult = client.getContent();

            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xmlResult);
            System.out.println(xmlToMap);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
